<script setup>
import { ref, computed, onMounted } from 'vue'; // 引入 computed
import axios from 'axios';
// 导入新组件
import DataChart from './components/DataChart.vue';
import CesiumMap from './components/CesiumMap.vue';

// --- 响应式状态定义 ---
const dataList = ref([]);
const errorMessage = ref('');
const loading = ref(false);

// 分页相关状态
const currentPage = ref(0); // 页码从0开始
const pageSize = ref(10);
const totalPages = ref(0);
const totalElements = ref(0);

// --- 方法定义 ---

// 分页数据获取函数
const fetchPagedData = async (page = 0) => {
  loading.value = true;
  try {
    // 使用模板字符串让 URL 更清晰
    const response = await axios.get(`/api/data/page?page=${page}&size=${pageSize.value}&sort=serverTimestamp,desc`);

    dataList.value = response.data.content;
    totalPages.value = response.data.totalPages;
    totalElements.value = response.data.totalElements;
    currentPage.value = response.data.number; // 使用后端返回的当前页码，更准确
    errorMessage.value = '';
  } catch (error) {
    console.error("获取分页数据失败:", error);
    errorMessage.value = '数据加载失败。请确保后端服务已启动。';
  } finally {
    loading.value = false;
  }
};

// 翻页函数 (现在 goToPage 已经可以处理所有逻辑)
const goToPage = (page) => {
  if (page >= 0 && page < totalPages.value) {
    fetchPagedData(page);
  }
};
// 上一页函数
const previousPage = () => {
  goToPage(currentPage.value - 1);
};

// 下一页函数
const nextPage = () => {
  goToPage(currentPage.value + 1);
};

// 计算页码按钮的逻辑 (之前在 methods 里的 getPageNumbers)
const getPageNumbers = computed(() => {
    const pages = [];
    const maxVisiblePages = 5; // 最多显示5个页码按钮

    if (totalPages.value <= maxVisiblePages) {
        for (let i = 1; i <= totalPages.value; i++) {
            pages.push(i);
        }
        return pages;
    }

    let startPage = Math.max(1, currentPage.value - 1);
    let endPage = Math.min(totalPages.value, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
        pages.push(i);
    }

    return pages;
});

// --- 生命周期钩子 ---
onMounted(() => {
  // 页面加载时获取第一页数据
  fetchPagedData(0);

  // 定时刷新当前页数据
  setInterval(() => {
    // 保持在当前页刷新
    fetchPagedData(currentPage.value);
  }, 10000); // 建议将刷新间隔延长一些，比如10秒，避免过于频繁
});
</script>

<template>
  <div class="container">
    <header>
      <h1>林木监测综合数据</h1>
    </header>
    
    <div class="dashboard">
      <div class="main-panel">
        <CesiumMap :dataList="dataList" />
        <div class="table-wrapper">
          <h2>数据列表</h2>
          <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-message">正在加载数据...</div>
          <table v-if="!loading">
            <thead>
              <tr>
                <th>设备 ID</th>
                <th>液流通道一</th>
                <th>液流通道二</th>
                <th>经度</th>
                <th>纬度</th>
                <th>上报时间（udt）</th>
                <th>液流速率 (j1)</th>
                <th>服务器时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-if="dataList.length === 0 && !errorMessage">
                <td colspan="6">暂无数据</td>
              </tr>
              <tr v-for="item in dataList" :key="item.id">
                <td>{{ item.did }}</td>
                <td>{{ item.j1 }}</td>
                <td>{{ item.j2 }}</td>
                <td>{{ item.gpsx }}</td>
                <td>{{ item.gpsy }}</td>
                <td>{{ item.udt }}</td>
                <td>{{ item.sapFlowRates ? item.sapFlowRates.j1.toFixed(2) + ' g/h' : '-' }}</td>
                <td>{{ item.serverTimestamp ? new Date(item.serverTimestamp).toLocaleString() : '-' }}</td>
                
              </tr>
            </tbody>
          </table>

          <!-- 分页控件 -->
          <div v-if="totalPages > 1" class="pagination">
            <div class="pagination-info">
              共 {{ totalElements }} 条数据，第 {{ currentPage + 1 }} / {{ totalPages }} 页
            </div>
            <div class="pagination-controls">
              <button 
                @click="previousPage" 
                :disabled="currentPage === 0"
                class="pagination-btn"
              >
                上一页
              </button>
              
              <!-- 页码按钮 -->
              <button 
                v-for="page in getPageNumbers" 
                :key="page"
                @click="goToPage(page - 1)"
                :class="['pagination-btn', { active: currentPage === page - 1 }]"
              >
                {{ page }}
              </button>
              
              <button 
                @click="nextPage" 
                :disabled="currentPage === totalPages - 1"
                class="pagination-btn"
              >
                下一页
              </button>
            </div>
          </div>
        </div>
      </div>

      <aside class="side-panel">
        <DataChart :dataList="dataList" />
      </aside>
    </div>
  </div>
</template>

<style scoped>
.container {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
}

header {
  text-align: center;
  margin-bottom: 1rem;
  border-bottom: 1px solid #eaeaea;
}

/* ---- 新的仪表盘布局样式 ---- */
.dashboard {
  display: flex;
  flex-wrap: wrap; /* 在小屏幕上允许换行 */
  gap: 1.5rem;
}

.main-panel {
  flex: 3;
  min-width: 600px; /* 设置最小宽度以优化布局 */
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.side-panel {
  flex: 1;
  min-width: 300px;
}

.table-wrapper, .chart-wrapper, .map-wrapper {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 1rem;
  background-color: #fff; /* 浅色模式下的默认背景 */
}

/* ---- 表格基础样式 ---- */
table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border-bottom: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

thead {
  background-color: #f8f8f8;
}

/* 默认（浅色模式）下的偶数行条纹样式 */
tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.error-message {
  color: #d8000c;
  background-color: #ffdddd;
  border: 1px solid #d8000c;
  padding: 10px;
  border-radius: 4px;
  text-align: center;
  margin-bottom: 1rem;
}

.loading-message {
  text-align: center;
  padding: 20px;
  color: #666;
  font-style: italic;
}

/* ---- 分页样式 ---- */
.pagination {
  margin-top: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 1rem;
}

.pagination-info {
  color: #666;
  font-size: 0.9rem;
}

.pagination-controls {
  display: flex;
  gap: 0.5rem;
  align-items: center;
}

.pagination-btn {
  padding: 8px 12px;
  border: 1px solid #ddd;
  background-color: #fff;
  color: #333;
  cursor: pointer;
  border-radius: 4px;
  font-size: 0.9rem;
  transition: all 0.2s ease;
}

.pagination-btn:hover:not(:disabled) {
  background-color: #f0f0f0;
  border-color: #999;
}

.pagination-btn.active {
  background-color: #007bff;
  color: white;
  border-color: #007bff;
}

.pagination-btn:disabled {
  background-color: #f5f5f5;
  color: #999;
  cursor: not-allowed;
  border-color: #ddd;
}

/* ---- 适配深色模式 ---- */
@media (prefers-color-scheme: dark) {
  header {
    border-bottom-color: #444;
  }
  
  .table-wrapper, .chart-wrapper, .map-wrapper {
    background-color: #1e1e1e; /* 深色模式下的卡片背景 */
    border-color: #444;
  }

  th, td {
    border-bottom-color: #444;
  }

  thead {
    background-color: #2c2c2c;
  }

  /* 深色模式下的偶数行条纹样式 */
  tbody tr:nth-child(even) {
    background-color: #252525;
  }

  .error-message {
    color: #ff9999;
    background-color: #5c1f1f;
    border: 1px solid #ff9999;
  }

  .loading-message {
    color: #aaa;
  }

  .pagination-info {
    color: #aaa;
  }

  .pagination-btn {
    background-color: #2c2c2c;
    border-color: #444;
    color: #fff;
  }

  .pagination-btn:hover:not(:disabled) {
    background-color: #3c3c3c;
    border-color: #666;
  }

  .pagination-btn.active {
    background-color: #007bff;
    color: white;
    border-color: #007bff;
  }

  .pagination-btn:disabled {
    background-color: #1a1a1a;
    color: #666;
    border-color: #333;
  }
}
</style>
<style>
/* Cesium InfoBox 深色模式样式修正 */
.cesium-infoBox {
  background: rgba(42, 42, 42, 0.95) !important; /* 设置一个带透明度的深灰色背景 */
  border: 1px solid #666;
}
.cesium-infoBox-title {
  background-color: #555;
  color: #aefeff !important; /* 将标题文字设为淡蓝色 */
}
.cesium-infoBox-body, .cesium-infoBox-body p {
  color: #ffffff !important; /* 将内容文字设为白色 */
}
</style>